#  Copyright (c) 2010
#  The Regents of the University of Michigan
#  All Rights Reserved

#  Permission is granted to use, copy, create derivative works, and
#  redistribute this software and such derivative works for any purpose,
#  so long as the name of the University of Michigan is not used in
#  any advertising or publicity pertaining to the use or distribution
#  of this software without specific, written prior authorization. If
#  the above copyright notice or any other identification of the
#  University of Michigan is included in any copy of any portion of
#  this software, then the disclaimer below must also be included.

#  This software is provided as is, without representation or warranty
#  of any kind either express or implied, including without limitation
#  the implied warranties of merchantability, fitness for a particular
#  purpose, or noninfringement.  The Regents of the University of
#  Michigan shall not be liable for any damages, including special,
#  indirect, incidental, or consequential damages, with respect to any
#  claim arising out of or in connection with the use of the software,
#  even if it has been or is hereafter advised of the possibility of
#  such damages.
import cPickle as pickle
import csv
import gzip
import hashlib
import itertools
import os
import sys

import libtorrent
from util import *

def pretty_print(top_n, metadata_root):
  ret = []
  join = os.path.join
  gopen = gzip.open
  bdecode = libtorrent.bdecode
  for hsh, count in top_n:
    torrent = bdecode(gopen(join(join(metadata_root, hsh[0].upper()),
                                 hsh.upper() + '.torrent.gz')).read())
    name = torrent['info']['name']
    ret.append((name, hsh, count))
  return ret


def top_n_with_metadata(n, metadata_root):
  enc = str.encode
  data = pickle.load(open('content_to_ip.dat'))
  data.reverse()

  metadata_files = []
  for i in range(16):
    metadata_files.extend(os.listdir(os.path.join(metadata_root, hex(i)[2].upper())))

  to_del = len('.torrent.gz')
  def make_sha_rev_tuple(x):
    hsh = x[:-to_del]
    return (hashlib.sha1(hsh.decode('hex')).digest(), hsh)

  metadata_files = dict(make_sha_rev_tuple(x) for x in metadata_files)

  def rev_sha(x):
    hsh, count = x
    hsh = metadata_files.get(hsh)
    if not hsh:
      print 'WARNING: %s has no metadata' % x[0].encode('hex')
    return (hsh, count) if hsh else None

  top_n = itertools.islice(itertools.ifilter(lambda x: x is not None,
                                             itertools.imap(rev_sha, data)), n)
  return pretty_print(top_n, metadata_root)


def main(argv):
  torrents = top_n_with_metadata(int(argv[0]), argv[1])
  outfyl = csv.writer(open(argv[2], 'w'))
  outfyl.writerows(torrents)


if __name__ == '__main__':
  main(sys.argv[1:])
